require 'client'
require 'server'
require 'listener'
require 'rexml/document'

module PCLink
  
  class Artist
    def initialize()
    end
  end 
  
  class StreamiumStation
    attr_reader :servers 

    def initialize(options)
      @options = options 
      @servers = []
      @nodes = []
      
      @servers << Server.new(options[:host]) if options[:host]
    end 

    def find_stations
      start_listener
      client = PCLink::Client.new(@options)
      client.send_hello
      puts "waiting for ack"
      sleep @options[:timeout]
      puts "#{@servers.length} server(s) found"
    end

    def list
      @nodes.each {|n| puts n}
    end

    def artists
      artists_nodes = get_listing_for("Artists")
      puts "found #{artists_nodes.length} artists"
      artists_nodes
    end 

    def tracks
      tracks_nodes = get_listing_for("All tracks")
      puts "found #{track_list.length} tracks"
      track_nodes
    end 
    
    def connect 
      puts "connecting to #{@servers[0]}"
      @nodes = @servers[0].list_nodes
    end 
    
    def update(info)
      process_message(info[:message]) if info.has_key?(:message)
    end

    def children(node = nil)
      @nodes
    end 
    
    def get_children_of(node)
      @servers[0].list_nodes(node.nodeid)
    end 
    
    private
    def get_listing_for(listing)
      listing_node = find_top_node(listing)
      @servers[0].list_nodes(listing_node.nodeid)
    end
    

    def find_top_node(name)
      node = nil
      @nodes.each do |n| 
        node = n if n.name.to_s == name
      end
      node
    end
    
    def process_message(msg)
      @servers << PCLink::Server.new(msg) if msg =~ /PCLinkServer/
    end

    def start_listener
      @listener = PCLink::Listener.new(@options)
      @listener.add_observer(self)
      @listener.start
    end

  end
end